using System;
using System.Text;

namespace HTML
{
	/// <summary>
	/// Summary description for ParseHTML.
	/// </summary>

	public class ParseHTML:Parse
	{
		public AttributeList GetTag()
		{
			AttributeList tag = new AttributeList();
			tag.Name = TagName;

			foreach(Attribute x in List)
			{
				tag.Add((Attribute)x.Clone());
			}

			return tag;
		}

		public String BuildTag()
		{
			StringBuilder buffer = new StringBuilder("<");

			buffer.Append(TagName);
			int i=0;
			while ( this[i]!=null )

			{// has attributes
				buffer.Append(" ");
				if ( this[i].Value == null )
				{
					if ( this[i].Delim!=0 )
						buffer.Append(this[i].Delim);
					buffer.Append(this[i].Name);
					if ( this[i].Delim!=0 )
						buffer.Append(this[i].Delim);
				}
				else
				{
					buffer.Append(this[i].Name);
					if ( this[i].Value!=null )
					{
						buffer.Append("=");
						if ( this[i].Delim!=0 )
							buffer.Append(this[i].Delim);
						buffer.Append(this[i].Value);
						if ( this[i].Delim!=0 )
							buffer.Append(this[i].Delim);
					}
				}
				i++;
			}
			buffer.Append(">");
			return buffer.ToString();
		}

		protected void ParseTag()
		{
			TagName = "";

			Clear();

			// Is it a comment?
			if ( (GetCurrentChar()=='!') &&
				(GetCurrentChar(1)=='-')&&
				(GetCurrentChar(2)=='-') )
			{
				while ( !Eof() )
				{
					if ( (GetCurrentChar()=='-') &&
						(GetCurrentChar(1)=='-')&&
						(GetCurrentChar(2)=='>') )
						break;
					if ( GetCurrentChar()!='\r' )
						_tagName.Append(GetCurrentChar());
					Advance();
				}
				_tagName.Append("--");
				Advance();
				Advance();
				Advance();
				ParseDelim = (char)0;
				return;
			}

			// Find the tag name
			while ( !Eof() )
			{
				if ( IsWhiteSpace(GetCurrentChar()) ||
					(GetCurrentChar()=='>') )
					break;
				_tagName.Append(GetCurrentChar());
				Advance();
			}

			EatWhiteSpace();

			// Get the attributes
			while ( GetCurrentChar()!='>' )
			{
				ParseName  = "";
				ParseValue = "";
				ParseDelim = (char)0;

				ParseAttributeName();

				if ( GetCurrentChar()=='>' ) 

				{
					AddAttribute();
					break;
				}

				// Get the value(if any)
				ParseAttributeValue();
				AddAttribute();
			}
			Advance();
		}


		public char Parse()
		{
			if (idleNextParse == true) 
			{
				idleNextParse = false;
				return (char)0;
			}

			if( GetCurrentChar()=='<' )
			{
				Advance();

				char ch=char.ToUpper(GetCurrentChar());
				if ( (ch>='A') && (ch<='Z') || (ch=='!') || (ch=='/') || (ch=='_')) 
				{
					ParseTag();
					return (char)0;
				}

				else return(AdvanceCurrentChar());
			}
			else return(AdvanceCurrentChar());
		}

		public void UndoParseTag()
		{
			idleNextParse = true;
		}

		private bool idleNextParse = false;
	}
}


